package com.yfs.cloud.service.impl;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.yfs.cloud.commons.BusinessException;
import com.yfs.cloud.commons.Constants;
import com.yfs.cloud.commons.ResultCode;
import com.yfs.cloud.config.BusinessProperties;
import com.yfs.cloud.service.SmsService;
import com.yfs.cloud.util.JsonUtil;

/**
* @Company: 影法師工作室
* @Description: 短信发送服务接口实现
* @author 影法師  
* @date 2020年8月29日 下午9:41:56 
* @version V1.0
 */
@SuppressWarnings("all")
@Service
public class SmsServiceImpl implements SmsService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private BusinessProperties businessProperties;

	/**
	 * 其实和 oss 的操作是极为类似的, 或者说阿里云的东西的操作都很类似, 就是先使用几个固定的值(appKey、appSecret等)new一个对象(下面的 client)再操作
	 */
	@Override
	public boolean send(Map<String, Object> param, String phone) {
		// 检查手机号码格式是否正确
		if (StringUtils.isBlank(phone) || !Constants.PHONE_PATTERN.matcher(phone).matches()) {
			throw new BusinessException(ResultCode.PHONE_ERROR);
		}
		DefaultProfile profile = DefaultProfile.getProfile(businessProperties.getSms().getRegionId(),
				businessProperties.getSms().getAccessKeyId(), businessProperties.getSms().getSecret());
		IAcsClient client = new DefaultAcsClient(profile);

		// 设置相关固定的参数
		CommonRequest request = new CommonRequest();
		// request.setProtocol(ProtocolType.HTTPS);
		request.setMethod(MethodType.POST);
		request.setDomain(businessProperties.getSms().getDomain());
		request.setVersion(businessProperties.getSms().getVersion());
		request.setAction(businessProperties.getSms().getAction());

		// 设置发送相关的参数
		request.putQueryParameter("PhoneNumbers", phone); // 手机号
		request.putQueryParameter("SignName", businessProperties.getSms().getSignName()); // 申请阿里云签名的名称
		request.putQueryParameter("TemplateCode", businessProperties.getSms().getTemplateCode()); // 申请阿里云模板的code
		request.putQueryParameter("TemplateParam", JsonUtil.obj2json(param)); // 验证码数据，转换json数据传递

		try {
			// 最终发送
			CommonResponse response = client.getCommonResponse(request);
			boolean success = response.getHttpResponse().isSuccess();
			return success;
		} catch (Exception e) {
			logger.info("手机号: {}, 短信模板号: {}, 短信签名: {} 发送失败.", phone, businessProperties.getSms().getTemplateCode(),
					businessProperties.getSms().getSignName());
			throw new BusinessException(ResultCode.SMS_SEND_FAILED);
		}
	}

}
